import 'dart:convert';
import 'package:spring_fairy/api/api.dart';
import 'package:spring_fairy/model/mood_track.dart';
import 'package:spring_fairy/model/mood_track_point.dart';

class MoodTrackAPI extends API {
  ///创建轨迹
  Future<MoodTrack?> createTrack(MoodTrack track) async {
    var response = await sendJSONPostRequest("/moodtracks/create", track.toJson());
    if(response == null) {
      return null;
    }
    return MoodTrack.fromJson(json.decode(response));
  }
  
  Future<MoodTrack?> createCustomTrack(MoodTrack moodTrack) async {
    var response = await sendJSONPostRequest("/moodtracks/custom/create", moodTrack.toJson());
    if(response == null) {
      return null;
    }
    return MoodTrack.fromJson(json.decode(response));
  }

  ///获取所有轨迹
  Future<List<MoodTrack>?> getAllTrack() async {
    var response = await sendGETRequest("/moodtracks/list");
    if(response == null) {
      return null;
    }
    var list =  json.decode(response);
    var result = <MoodTrack>[];
    for(int i = 0 ; i < list.length ; i++) {
      result.add(MoodTrack.fromJson(list[i]));
    }
    return result;
  }

  ///添加标记点
  Future<MoodTrackPoint?> addPoint(int trackId,MoodTrackPoint point) async {
    var response = await sendJSONPostRequest("/moodtracks/points/create?trackId=${trackId}", point.toJson());
    if(response == null) {
      return null;
    }
    return MoodTrackPoint.fromJson(json.decode(response));
  }
  

  ///获取某条轨迹的所有标记点
  Future<List<MoodTrackPoint>?> getPointsByTrack(int trackId) async {
    var response = await sendGETRequest("/moodtracks/$trackId/points");
    if (response == null) return null;
    var list = json.decode(response);
    return list.map<MoodTrackPoint>((e) => MoodTrackPoint.fromJson(e)).toList();
  }

  ///删除标记点
  Future<bool> deletePoint(int pointId) async {
    var response = await sendGETRequest("/moodtracks/points/delete?pointId=$pointId");
    return response != null;
  }

  ///更新标记点
  Future<MoodTrackPoint?> updatePoint(MoodTrackPoint point) async {
    var response = await sendJSONPostRequest("/moodtracks/points/update", point.toJson());
    if (response == null) return null;
    return MoodTrackPoint.fromJson(json.decode(response));
  }
}